package utl.mofen.script;

import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;

import utl.mofen.impl.BsConfigLoader;
import utl.mofen.intf.IDBOperator;
import utl.mofen.utils.StringUtil;

public class ScriptLoader extends BsConfigLoader {
	protected IDBOperator dbOperator;

	// 使用连接池，可能连接池中的Connection可能不可用，用的时候获取
	String dbid = "";

	public ScriptLoader(IDBOperator operator) {
		this.dbOperator = operator;
	}

	public ScriptLoader(String dbid) {
		this.dbid = dbid;
	}

	public byte[] getData(String strIndex, String strVer) throws Exception {

		String sql = "SELECT TOP 1 FData, FVer, FKind"
				+ // 取一个配置,如果没有对应的版本,去默认配置
				"  FROM sys_Config" + "  WHERE (FCode = '" + strIndex + "'"
				+ "         OR (FAliasCode = '" + strIndex
				+ "' and (ISNULL(FAliasCode, '') <> '')))"
				+ "     AND (FVer = '" + strVer
				+ "' OR ISNULL(FVer,'')='') --默认版本也列出"
				+ "     AND FData IS NOT NULL"
				+ "  ORDER BY ISNULL(FVer,'') DESC  --默认的放在最后";

		if (dbOperator == null) {
			if (this.dbid.equals("")) {
				throw new Exception("未指定dbid配置!");
			}
			IDBOperator dbOpera = ScriptObjectFactory.getDBOperator(this.dbid);
			try {
				ResultSet rs = dbOpera.queryData(sql);
				if (rs.next()) {
					byte[] buf = rs.getBytes(1);
					return buf;
				} else {
					throw new Exception(String.format("无法找到相应的配置%s", strIndex));
				}
			} finally {
				dbOpera.close();
			}
		} else {
			ResultSet rs = dbOperator.queryData(sql);
			if (rs.next()) {
				byte[] buf = rs.getBytes(1);
				return buf;
			} else {
				throw new Exception(String.format("无法找到相应的配置%s", strIndex));
			}
		}

	}

	public String getString(String strIndex, String strVer) throws Exception {
		byte[] buf = this.getData(strIndex, strVer);
		String encodedString = new String(buf);
		// System.out.println(encodedString);
		return encodedString;

	}

	public String getString(String strIndex, String strVer, String decode)
			throws Exception {
		byte[] buf = this.getData(strIndex, strVer);
		String encodedString = "";
		try
		{
			if (StringUtil.stringIsEmpty(decode)) {
				encodedString = new String(buf);
			} else {
				encodedString = new String(buf, decode);
			}
		}catch (UnsupportedEncodingException e)
		{
			throw new Exception("不支持的解码方式:" + decode);
		}
		return encodedString;
	}	

}
